<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>Document</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous" />
  <link rel="stylesheet" href="/public/css/login.css" />
  <style>
    .header {
      margin: 30px;
    }
  </style>
</head>

<body>
  <div class="main">
    <div class="header">
      <a href="/">
        <img src="/public/img/logo3.png" alt="" style="max-width: 80px" />
      </a>
    </div>
    {{block 'content'}}
    <h3 class="header">用户登录</h3>
    <form id="login_form">
      <div class="form-group">
        <label for="">邮箱</label>
        <input type="email" class="form-control email_input" id="" name="email" placeholder="Email" autofocus />
      </div>
      <div class="form-group">
        <label for="">密码</label>
        <a class="pull-right" href="">忘记密码？</a>
        <input type="password" class="form-control password_input" id="" name="password" placeholder="Password" />
      </div>
      <div class="checkbox">
        <label> <input type="checkbox" class="remember_me" />记住我 </label>
      </div>
      <button type="submit" class="btn btn-info btn-block">登录</button>
    </form>
    <div class="message message_">
      <p>没有账号? <a href="/login/register">点击创建</a>.</p>
    </div>
    {{/block}}
  </div>
  <script src="/node_modules/jquery/dist/jquery.min.js"></script>
  {{block 'script'}}
  <script>
    if (localStorage.getItem("remember_me")) {
      $(".remember_me").prop("checked", true);
      const email = localStorage.getItem("remember_me");
      const password = localStorage.getItem(email);
      $(".email_input").val(email);
      $(".password_input").val(password);
    }
    $("#login_form").on("submit", (e) => {
      e.preventDefault();
      const formData = $("#login_form").serialize();
      $.ajax({
        url: "/login",
        type: "POST",
        data: formData,
        dataType: "json", // 返回的json数据解析为对象
        success: (data) => {
          if (data.err_code === 0) {
            if ($(".remember_me").prop("checked")) {
              // 存储到本地
              localStorage.setItem("remember_me", $(".email_input").val());
              localStorage.setItem(
                $(".email_input").val(),
                $(".password_input").val()
              );
            } else {
              localStorage.clear();
            }
            window.alert("登陆成功");
            window.location.href = "/";
          } else if (data.err_code === 1) {
            window.alert("用户尚未注册，请注册后再登录");
            window.location.href("/login/register");
          } else if (data.err_code === 500) {
            window.alert("服务器繁忙，请刷新或者等待后重试");
          }
        },
      });
    });
  </script>
  {{/block}}
</body>

</html>